package RMI;

import java.io.Serializable;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import Entidades.Filial;
import Entidades.Projeto;
import Entidades.Tarefa;
import Entidades.Usuario;
import Util.Controle;

public class Server extends UnicastRemoteObject implements IFilial {

	private static final long serialVersionUID = 1L;

	public Server() throws RemoteException {
		super();
	}

	public void startServer() {
		System.out.println("Iniciando Servidor RMI...");

		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new RMISecurityManager());
			System.out.println("Security manager installed.");
		} else
			System.out.println("Security manager already exists.");

		try {
			LocateRegistry.createRegistry(1099);
			System.out.println("java RMI registry created.");
		} catch (RemoteException e) {
			System.out.println("java RMI registry already exists.");
		}

		try {
			Server obj = new Server();
			String serverAddress = Controle.getLocalAddress();

			Naming.rebind(serverAddress, obj);

			System.out.println("PeerServer bound in registry");
		} catch (Exception e) {
			System.err.println("RMI server exception:");
			e.printStackTrace();
		}

	}

	@Override
	public String ping() throws RemoteException {
		return "PING OK " + Controle.getFilialnumero();
	}

	@Override
	public ArrayList<Projeto> listaProjetos() throws RemoteException {
		return Filial.getInstance().getProjetos();
	}

	@Override
	public String getServerAddress() throws RemoteException {
		return Controle.getLocalAddress();
	}

	@Override
	public ArrayList<Tarefa> listaTarefass(String ProjetoCodigo)
			throws RemoteException {
		return Filial.getInstance().getProjeto(ProjetoCodigo).getTarefas();
	}

	@Override
	public ArrayList<Usuario> listaUsuarios() throws RemoteException {
		return Filial.getInstance().getUsuarios();
	}

}
